<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <div class="app-container" >
          <el-form :model="form" ref="form" size="small" :rules="rules" v-show="showSearch">

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="采购类别:">
                  <el-radio-group v-model="form.goodsType">
                    <el-radio
                      v-for="dict in dict.type.goods_type"
                      :key="dict.value"
                      :label="dict.value"
                    >{{ dict.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="供应商:" prop="supplierId">
                  <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable @change="selectSupplier"
                             style="width: 260px">
                    <el-option v-for="dict in dict.type.goods_supplier" ref="myselectSsupplier"
                               :key="dict.value" :label="dict.label" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>


              <el-col :span="8">
                <el-form-item label="采购类型:" prop="ywType">
                  <el-select v-model="form.ywType" placeholder="请选择采购类型" clearable style="width: 180px;">
                    <el-option v-for="dict in dict.type.caigou_type"
                               :key="dict.value" :label="dict.label" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="定金:" prop="dingjin">
                  <el-input-number v-model="form.dingjin" :precision="2" :min="0" style="width: 260px;"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="运费:">
                  <el-input-number v-model="form.shippingFee" :precision="2" :min="0"  style="width: 260px;"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.shippingFee>0">
                <el-form-item label="运费合并付款:">
                  <el-radio-group v-model="form.depositMerge">
                    <el-radio v-for="dict in dict.type.yes_no"
                              :key="dict.value" :label="dict.value">{{ dict.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开户行:">
                  <el-input v-model="form.bankName" disabled style="width: 260px;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="银行行号:">
                  <el-input v-model="form.bankNo" disabled style="width: 260px;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="银行账号:">
                  <el-input v-model="form.accountNo" disabled style="width: 260px;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="附件:">
                  <file-upload v-model="form.files"></file-upload>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="备注:">
                  <el-input v-model="form.remark" style="width: 260px;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                  <el-button type="primary" plain icon="el-icon-plus" size="mini"  @click="handleSelectPleaseBuy">添加采购产品</el-button>
              </el-col>
            </el-row>
          </el-form>

      <el-table :data="dataList" ref="dragTable" row-key="id" v-loading="loading"  show-summary :summary-method="getSummaries">
        <el-table-column align="center" label="序号" type="index" width="50">
          <template slot-scope="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column  label="请购单号" align="center" prop="nos"/>
        <el-table-column  label="订单单号" align="center" prop="projectNo"/>
        <el-table-column  label="产品编码" align="center" prop="goodsCode"/>
        <el-table-column  label="产品名称" align="center" prop="goodsName" show-overflow-tooltip/>
        <el-table-column  label="产品型号" align="center" prop="goodModel"/>
        <el-table-column label="成品/材料" align="center" key="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.goodsType"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="160">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.goodsBuyPrice"  @change="updateTotalCost(scope.row)" size="mini"
                             :min="0" :precision="4"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="采购数量" width="160" prop="shengyu">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.shengyu" @change="updateTotalCost(scope.row)" size="mini" :precision="4"
                             ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="重量" width="160" prop="dun">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.dun" size="mini" :precision="4"
                              @change="updateTotalCost(scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="总价" width="160" prop="goodsBuyTotal">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.goodsBuyTotal" size="mini" :precision="4"
                              @change="updateBuyPriceByTotal(scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="140">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="showChild(scope.row)">采购明细</el-button>
            <el-popconfirm :title="`确认删除 `+scope.row.goodsName+` 数据项？`" @confirm="handleDelete(scope.row)"
                           style="margin-left: 10px;">
              <el-button icon="el-icon-delete" size="mini" slot="reference" type="text"
                         v-hasPermi="['develop:ProjectBaseInfo:remove']">删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div slot="footer" class="dialog-footer">

      <el-button type="primary" @click="submitCgd" v-if="">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <please-buy-select-list ref="pleaseBuyList" @ok="getList"></please-buy-select-list>
    <goods-salebuyLists ref="showForm" @ok="getList"></goods-salebuyLists>
  </el-dialog>
</template>

<script>
import {accAdd, accDiv, accMul, addAction, deleteAction, getAction, getById, updateAction} from '@/api/manage';
import { list } from "@/api/develop/goodsSaledo";
import PleaseBuySelectList from "@/views/develop/lvBuy/module/PleaseBuySelectList.vue";
import GoodsSalebuyLists from "@/views/develop/lvBuy/module/GoodsSalebuyLists.vue";

export default {
  name: "LvBuyAddFormListNew",
  dicts: ['goods_customer', 'company', 'yes_no', 'goods_supplier', 'goods_type','caigou_type'],
  components: {
    GoodsSalebuyLists,
    PleaseBuySelectList,
  },
  data() {
    return {

      // 遮罩层
      title: "采购单",
      loading: false,
      open: false,
      // 选中数组
      ids: [],
      buyId: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库信息管理表格数据
      dataList: [],
      dateRange: [],
      form: {
        supplierId: null,
        supplierName: null,
        dingjin: null,
        kaihuhang: null,
        shippingFee: null,
        depositMerge: null,
        zhanghao: null,
        hanghao: null,
        remark: null,
        goodsType: "0",
      },
      rules: {
        supplierId: [
          {required: true, message: "请选择供应商", trigger: "blur"}
        ],
        bankName: [
          {required: true, message: "请输入开户行", trigger: "blur"}
        ],
        accountNo: [
          {required: true, message: "请输入银行账号", trigger: "blur"}
        ],
        ywType: [
          {required: true, message: "请选择采购类型", trigger: "blur"}
        ],
        depositMerge: [
          {required: true, message: "请选择运费是否合并付款", trigger: "blur"}
        ],
      },
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        name: null,
        model: null,
        addr: null,
        tel: null,
        bankName: null,
        bankNo: null,
        info: null,
        isdo: "0",
        delFlag: null,
        remark: null,
        type: null,
        orderByColumn: 'create_time',
        isAsc: 'desc'
      },
      url: {
        list: '/goodsSalebuyall/goodsSalebuyall/list',
        remove: '/goodsSalebuyall/goodsSalebuyall/deleteCg/',
        goodsSupplierById: '/goodsSupplier/goodsSupplier/',
        export: '/goodsOrderIn/goodsOrderIn/export',
        insertForCg: '/goodsSalebuy/goodsSalebuy/insertForCg',
        updateCgd: '/goodsSalebuyall/goodsSalebuyall/updateCgd',
        submitProject: '/projectBaseInfo/projectBaseInfo/submitProject',
        submitGoodsbuyall: '/goodsSalebuyall/goodsSalebuyall/edit',
      },
      tableMaxHeight: window.innerHeight - 900,
    };
  },
  created() {

  },
  methods: {
    reset() {
      this.form = {
        id: null,
        supplierId: null,
        supplierName: null,
        dingjin: null,
        bankName: null,
        bankNo: null,
        accountNo: null,
        remark: null,
        goodsType: "0",
      };
      this.resetForm("form");
    },

    showChild(row) {
      this.$refs.showForm.showsalebuyList(row);
    },
    dingjinValidator(rule, value, callback) {
      if (value === 0) {
        callback(new Error('定金不能为0'));
      } else {
        callback();
      }
    },
    selectSupplier(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectSsupplier;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.supplierName = arr[i].label;
            getById(this.url.goodsSupplierById, value).then(response => {
              that.form.bankName = response.data.bankName;//开户行
              that.form.accountNo = response.data.accountNo;//账号
              that.form.bankNo = response.data.bankNo;//行号
              //that.form.supplierId = response.data.id;//id
            });
          }
        }
      })
    },
    getList() {
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    handleUpdate(row) {
      this.form = row;
      this.open = true;
      this.loading = false;
      this.queryParams.mainId =row.id;
      this.buyId =row.id;
      this.getList();
    },

    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        this.$modal.msgSuccess("删除成功");
        this.handleQuery();
      }).catch(() => {
      });
    },
    updateTotalCost(row) {
      let that = this;
      if(row.goodsType === "0"){
        if (row.shengyu && row.goodsBuyPrice) {
          let totleCost = accMul(row.shengyu, row.goodsBuyPrice);
          that.$set(row, "goodsBuyTotal", totleCost);
        }
      }
      if(row.goodsType === "1"){
        if (row.dun && row.goodsBuyPrice) {
          let totleCost = accMul(row.dun, row.goodsBuyPrice);
          that.$set(row, "goodsBuyTotal", totleCost);
        }
      }
      this.updateGoodsBuyAll(row);
    },


    updateBuyPriceByTotal(row) {
      let that = this;
      if(row.goodsType === "0"){
        if (row.shengyu && row.goodsBuyTotal) {
          let totalCost = accDiv(row.goodsBuyTotal, row.shengyu);
          that.$set(row, "goodsBuyPrice", totalCost);
        }
      }
      if(row.goodsType === "1"){
        if (row.dun && row.goodsBuyTotal) {
          let totalCost = accDiv(row.goodsBuyTotal, row.dun);
          that.$set(row, "goodsBuyPrice", totalCost);
        }
      }
      this.updateGoodsBuyAll(row);
    },


    updateGoodsBuyAll(row){
      updateAction(this.url.submitGoodsbuyall, row).then(response => {

      })
    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.mainId =this.buyId;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.dataList = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    submitCgd() {
      let that = this;
      let arrays = that.dataList;
      for (let i = 0; i < arrays.length; i++) {
        if (arrays[i].goodsBuyPrice === 0) {
          that.$modal.msgError(arrays[i].goodsName + ":产品单价不能为0");
          return;
        }
        if (arrays[i].shengyu === 0) {
          that.$modal.msgError(arrays[i].goodsName + ":采购数量不能为0");
          return;
        }

      }
      that.$refs["form"].validate(valid => {
        if (valid) {
          const goodsSaledo = Object.assign({});
          goodsSaledo.supplierId = that.form.supplierId;
          goodsSaledo.supplierName = that.form.supplierName;
          goodsSaledo.bankName = that.form.bankName;
          goodsSaledo.accountNo = that.form.accountNo;
          goodsSaledo.bankNo = that.form.bankNo;
          goodsSaledo.goodsType = that.form.goodsType;
          goodsSaledo.dingjin = that.form.dingjin;
          goodsSaledo.shippingFee = that.form.shippingFee;
          goodsSaledo.depositMerge = that.form.depositMerge;
          goodsSaledo.remark = that.form.remark;
          goodsSaledo.columns = that.dataList;
          goodsSaledo.mainId = that.buyId;
          addAction(this.url.updateCgd, goodsSaledo).then(response => {
            this.$modal.msgSuccess("提交成功!");
            this.open = false;
            that.$emit('ok');
            this.handleQuery();
          }).catch(() => {
          });
        }
      });
    },

    changeGoodsType(){
      this.getList();
    },

    handleSelectPleaseBuy(){
      this.$refs.pleaseBuyList.show(this.buyId);
    },

    getSummaries(param) {
      // console.log(param);
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if ( column.property === "shengyu" || column.property === "goodsBuyTotal" || column.property === "dun") {
          sums[index] = values.reduce((prev, curr) => {

            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev , curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },



  }
};
</script>
